#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include "ipckernel.h"
#include "wmark_dev.h"
#include "ipckernel.h"
#define DEV "/dev/wmark_dev"

int open_ipc_dev(ipc_dev_info_t *dev_info)
{
	if (!dev_info) {
		printf("info == NULL\n");
		return -1;
	}
	int fd = open(DEV,O_WRONLY);
	if (fd==-1) 
	{
		perror(DEV);
		return -1;
	}

	dev_info->dev_fd = fd;

	return 0;
}

int dev_send_fd(ipc_dev_info_t *dev_info) {
	int ret = -1;
	if (!dev_info) {
		printf("info == NULL\n");
		return -1;
	}

	wmark_dev_ioctl_t msg;
	msg.buf_fd = dev_info->buf_fd;
	msg.buf_len = dev_info->buf_len;

	ret = ioctl(dev_info->dev_fd, SET_FLAG_CMD, &msg);
	if (ret) {
		printf("%s %d fail!!!\n", __func__, __LINE__);
	}

	return ret;
}

int dev_send_fds(ipc_dev_info_t *dev_info, wmark_dev_ioctl_t *msg) {
	int ret = -1;
	if (!dev_info) {
		printf("info == NULL\n");
		return -1;
	}

	ret = ioctl(dev_info->dev_fd, SET_BUFS_CMD, msg);
	if (ret) {
		printf("%s %d fail!!!\n", __func__, __LINE__);
	}

	return ret;
}

int dev_receive_fd(ipc_dev_info_t *dev_info)
{
	if (!dev_info) {
		printf("info == NULL\n");
		return -1;
	}

	wmark_dev_ioctl_t msg;

	int ret = ioctl(dev_info->dev_fd, GET_FLAG_CMD, &msg);
	if (ret) {
		printf("%s %d fail!!!\n", __func__, __LINE__);
		return -1;
	}

	dev_info->buf_fd = msg.buf_fd;
	dev_info->buf_len = msg.buf_len;

	printf("%s buf_fd=%d buf_len=%d\n", __func__, dev_info->buf_fd, dev_info->buf_len);

	return ret;
}

int dev_receive_fds(ipc_dev_info_t *dev_info ,wmark_dev_ioctl_t *msg)
{
	if (!dev_info) {
		printf("info == NULL\n");
		return -1;
	}

	int ret = ioctl(dev_info->dev_fd, GET_BUFS_CMD, msg);
	if (ret) {
		printf("%s %d fail!!!\n", __func__, __LINE__);
		return -1;
	}

	return ret;
}

int close_ipc_dev(ipc_dev_info_t *dev_info)
{
	if (!dev_info) {
		printf("info == NULL\n");
		return -1;
	}
	close(dev_info->dev_fd);
	return 0;
}
